<?php
namespace app\common\service;

use Firebase\JWT\JWT;
use Firebase\JWT\Key;
use think\facade\Log;
use think\facade\Env;
use app\common\library\Token;

class JwtService
{

    // 生成JWT
    public static function generateToken($userId, $user = [],$iss = '')
    {
        try {
            $expireTime = 3600;
            $secretKey = Env::get('secretkey.authkey', 'your_secret_key');
            $issuedAt = time();
            $payload = [
                'iss' => $iss,
                'iat' => $issuedAt,
                'exp' => $issuedAt + $expireTime,
                'userId' => $userId,
                'user' => $user
            ];
            $token = JWT::encode($payload, $secretKey, 'HS256');
            Log::info("为用户生成的令牌 $userId");
        } catch (\Exception $e) {
            Log::error("令牌生成失败: " . $e->getMessage());
            throw new \Exception("令牌生成失败");
        }
        return $token;
    }
    public static function validateUserToken($token)
    {
        try {
            $secretKey = Env::get('secretkey.authkey', 'your_secret_key');
            $decoded = JWT::decode($token, new Key($secretKey, 'HS256'));
            $result = Token::get($token);
            if (!$result) {
                Log::error("令牌无效或已过期DB");
                throw new \Exception("令牌无效或已过期DB");
            }
            if ($decoded->exp < time()) {
                Log::error("令牌已过期JWT");
                throw new \Exception("令牌已过期JWT");
            }
            // Log::info("Token validated for user " . $decoded->userId);
            return $decoded;
        } catch (\Exception $e) {
            Log::error("Token validation failed: " . $e->getMessage());
            throw new \Exception($e->getMessage());
        }
    }
}